package org.springblade.modules.repair.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.modules.repair.dto.SystemMsgDTO;
import org.springblade.modules.repair.entity.MaintainMsg;
import org.springblade.modules.repair.service.MaintainMsgService;
import org.springblade.modules.repair.vo.MaintainMsgVO;
import org.springblade.modules.repair.vo.MsgTypeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Date 9:48 2022/5/30
 * @Description {
 *   平台消息
 * }
 * @Author lsay
 **/
@RestController
@RequestMapping("/msg")
@AllArgsConstructor
public class MsgController {

	private final MaintainMsgService msgService;

	/**
	 * 获取消息分类及对应未读消息数量
	 * @return
	 */
	@TenantIgnore
	@GetMapping("/type")
	public R<List<MsgTypeVO>> listMsgType(){
		return R.data(msgService.listMsgType());
	}

	/**
	 * 根据消息分类获取消息列表
	 * @return
	 */
	@TenantIgnore
	@GetMapping("/page")
	public R<IPage<MaintainMsgVO>> selectMsgPage(String keyword, String typeIds, Integer status, Integer bType, Query query){
		return R.data(msgService.selectMsgPage(keyword,typeIds,status,bType, Condition.getPage(query)));
	}

	/**
	 * 更改消息状态为已读
	 * @param typeIds
	 * @return
	 */
	@TenantIgnore
	@PutMapping()
	public R<Boolean> readBath(@RequestBody List<Long> typeIds){
		return R.status(msgService.readBath(typeIds, AuthUtil.getUserId()));
	}

	/**
	 * 更改消息状态为已读
	 * @param id
	 * @return
	 */
	@TenantIgnore
	@PutMapping("/{id}")
	public R<Boolean> read(@PathVariable Long id){
		return R.status(msgService.read(id,AuthUtil.getUserId()));
	}

	/**
	 * 消息中台-发送系统消息
	 */
	@TenantIgnore
	@PostMapping("/send/msg")
	public R sendMsg(@RequestBody SystemMsgDTO msg) {
		try {
			MaintainMsg maintainMsg = new MaintainMsg();
			BeanUtils.copyProperties(msg, maintainMsg);
			Long msgId = msgService.sendMsg(maintainMsg, msg.getUserIds(), msg.getTenantId());
			return R.data(msgId,"发送成功");
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

	/**
	 * 更改消息状态为已读 全部
	 * @param
	 * @return
	 */
	@TenantIgnore
	@PutMapping("/read/all")
	public R<Boolean> readAll(){
		return R.status(msgService.readAll(AuthUtil.getUserId()));
	}
}
